extends Spatial


export(PoolStringArray) var tile_plan = [
	"x-----x",
	"|#### d",
	"|     |",
	"|. .. |",
	"|. .. |",
	"|.    |",
	"|     |",
	"|cccc_|",
	"|,s,,,|",
	"x-----x"
	]
	
onready var Wall = $prototypes/wall
onready var Cubboard = $prototypes/cubboard
onready var Floor = $prototypes/floor
onready var Door = $prototypes/door
onready var Chair = $prototypes/chair

var astar = AStar.new()
var door_position = Vector3(0,0,0)
var player_start_position = Vector3(0,0,0)
var seats = []

signal build

# Called when the node enters the scene tree for the first time.
func _ready():
	spawn_tiles()
	connect_astar()
	$prototypes.visible = false
	emit_signal("build")

func spawn_tiles():
	var z = 0.0
	for row in tile_plan:
		var x = 0.0
		for c in row:
			if c == "|":
				spawn_thing(Wall.duplicate(), x, z)
			elif c == "-":
				var w = spawn_thing(Wall.duplicate(), x, z)
				w.rotate(Vector3(0,1,0), deg2rad(90))
			elif c == "x":
				spawn_thing(Wall.duplicate(), x, z)
				var w = spawn_thing(Wall.duplicate(), x, z)
				w.rotate(Vector3(0,1,0), deg2rad(90))
			elif c == "d":
				spawn_thing(Door.duplicate(), x, z)
				door_position = Vector3(x,0,z)
			elif c == ".":
				spawn_thing(Cubboard.duplicate(), x, z)
			elif c == "#":
				var spot = Cubboard.duplicate()
				spot.at_window = true
				spawn_thing(spot, x, z)
			elif c == "c":
				spawn_thing(Cubboard.duplicate(), x, z)
			elif c == "s":
				var s = Chair.duplicate()
				spawn_thing(s, x, z)
				seats.append(s)
			elif c == "_":
				player_start_position = Vector3(x,0,z)
				pass # not walkable for npcs
			elif c == ",":
				pass # not walkable for npcs
			elif c == " ":
				mark_walkable(x,z, row.length())
				pass
			else:
				print("unknown tile", c)
			spawn_thing(Floor.duplicate(), x, z)
			x += 1.0
		z += 1.0

func spawn_thing(thing, x, z):
	thing.transform.origin.x = x
	thing.transform.origin.z = z
	add_child(thing)
	return thing

func mark_walkable(x,z, z_size):
	astar.add_point((z*z_size)+x,Vector3(x,0,z))
	
func connect_astar():
	var points = astar.get_points()
	for p in points:
		var pos1 = astar.get_point_position(p)
		for p2 in points:
			var pos2 = astar.get_point_position(p2)
			if pos1.distance_squared_to(pos2) <= 1.0:
				if p != p2 and not astar.are_points_connected(p,p2):
					astar.connect_points(p, p2)
			
		
	
